//
//  GTGZImageDownloadedView.m
//  GTGZLibrary
//
//  Created by fanty on 13-4-22.
//  Copyright (c) 2013年 fanty. All rights reserved.
//

#import "CImageDownloadedView.h"
#import "CImageDownloadedManager.h"
@interface CImageDownloadedView()

-(void)imageLoadingFinish:(NSNotification*)notification;
@end


@implementation CImageDownloadedView

@synthesize url;
@synthesize thumbnailSize;
@synthesize status;
-(id)init{
    self=[super init];
    if(self){
        self.thumbnailSize=CGSizeMake(150.0f, 150.0f);
        status=ImageViewDownloadedStatusNone;
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        self.thumbnailSize=CGSizeMake(150.0f, 150.0f);
        status=ImageViewDownloadedStatusNone;
    }
    return self;
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)setUrl:(NSString *)value{
    if([url isEqualToString:value])return;
    
    status=ImageViewDownloadedStatusNone;
    if([self.url length]>0){
        [[CImageDownloadedManager sharedInstance] remove:self.url size:self.thumbnailSize];
    }
    
    url=nil;
    
    self.image=nil;

    if([value length]<1){
        [[NSNotificationCenter defaultCenter] removeObserver:self];
        [self imageDownloadedStatusChanged];
        //stop download  and no image
        return;
    }
    
    //start download

    url=value;

    self.image=[[CImageDownloadedManager sharedInstance] appendUrl:self.url size:self.thumbnailSize];

    if(self.image==nil){
        if([[CImageDownloadedManager sharedInstance] checkImageIsDownloadedByUrl:self.url size:self.thumbnailSize]){
            status=ImageViewDownloadedStatusFail;
        }
        else{
            status=ImageViewDownloadedStatusDownloading;
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageLoadingFinish:) name:NotificationImageLoadingFinish object:nil];
        }
    }
    else{
        status=ImageViewDownloadedStatusFinish;
    }
    
    //check image is download or failed  or finish
    [self imageDownloadedStatusChanged];

}

-(void)imageLoadingFinish:(NSNotification*)notification{
    if(self.status!=ImageViewDownloadedStatusFinish){
        NSString* __url=notification.object;
        if([self.url isEqualToString:__url]){
            UIImage* img=[[CImageDownloadedManager sharedInstance] get:self.url size:self.thumbnailSize];
            if(img!=nil){
                status=ImageViewDownloadedStatusFinish;
                self.image=img;
                [[NSNotificationCenter defaultCenter] removeObserver:self];
            }
            else{
                status=ImageViewDownloadedStatusFail;
            }
            //image is finish
            [self imageDownloadedStatusChanged];

        }
    }
}

-(void)imageDownloadedStatusChanged{
    
}

@end
